import { Component, Input, OnInit } from '@angular/core';
import { BdOperationProcessListComponent } from '../list/list.component';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { BasicDataService } from '../../basic-data.service';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { AuthDictService } from '../../../../system/dict/service/dict.service';
import { environment } from '@env/environment';

@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.less']
})
export class BdOperationProcessEditComponent implements OnInit{
	@Input()
	record: any;
	form: FormGroup;

	shipLandList = [];
	tallyTypeList = [];
	ynList = environment.dict.yesOrNoStr;

	constructor(
		private fb: FormBuilder,
		private basicDataService: BasicDataService,
		private modalRef: NzModalRef,
		private dictService: AuthDictService) {
		this.dictService.dictionary(environment.dict.SHIP_LAND, 1).subscribe(res => {
			this.shipLandList = res;
		});
		this.dictService.dictionary(environment.dict.TALLY_TYPE, 1).subscribe(res => {
			this.tallyTypeList = res;
		});
		this.form = fb.group({
			id: [null],
			name: [null, [Validators.required]],
			shipLand: [null, [Validators.required]],
			tallyType: [null, [Validators.required]],
			sort: [null, [Validators.required]],
			isActivity: [null, [Validators.required]],
			isProcess: [null, [Validators.required]],
		});
	}

	ngOnInit(): void {
		if (this.record.id) {
			this.form.patchValue(this.record);
		}
	}

	saveAndClose(): any {
		if (!this.validate()) {
			return false;
		}
		const postData = {
			...this.form.value
		};
		this.basicDataService.operationProcessSubmit(postData).subscribe((res: any) => {
			this.modalRef.close(true);
		});
	}

	close() {
		this.modalRef.close();
	}

	validate() {
		for (const key in this.form.controls) {
			if (this.form.controls.hasOwnProperty(key)) {
				const element = this.form.controls[key];
				element.markAsDirty();
				element.updateValueAndValidity();
			}
		}
		return this.form.valid;
	}
}
